package com.zkingsoft.zkingbase.services;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.zkingsoft.zkingbase.R;
import com.zkingsoft.zkingbase.manager.OkHttpManager;
import com.zkingsoft.zkingbase.utils.FileUtils;

import java.io.File;

/***
 * Created by ytf on 2017/3/3 003.
 * Description: 用于更新的service
 *
 */
public class UpdateService extends Service
{

    private OkHttpManager manager;
    //控制只初始化一次
    private boolean isFirst = true;
    //获得通知管理器
    NotificationManager mNotiManager;
    //构建包装意图
    PendingIntent pendingIntent;
    //builder对象
    NotificationCompat.Builder mBuilder;

    public UpdateService()
    {
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        manager = OkHttpManager.getInstance();
        mNotiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        if (intent != null)
        {
            String url = intent.getStringExtra("download_url");
            String path = intent.getStringExtra("filepath");
            if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(path))
            {
                downloadPackage(url, path);
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    //解决因为频繁调用进度刷新导致卡顿问题
    private int oldProg = 0;

    private void downloadPackage(String url,String filePath)
    {

        String path = filePath + "/" + getResources().getString(R.string.app_name) + ".apk";
        manager.download(url, filePath, new OkHttpManager.ResultCallback<File>()
        {
            @Override
            public void onDownloadProgress(long progress, long allLength, boolean done)
            {
                float p = 100f / allLength;
                if(done)
                {
                    mNotiManager.cancelAll();
                }else
                {
                    //避免频繁调用导致卡顿
                    int prog = (int) (p * progress);
                    if(oldProg != prog)
                    {
                        showProgressInNotify(prog);
                        oldProg = prog;
                    }
                }
            }

            @Override
            public void onError(String simpleMsg, Exception e)
            {
                Log.e("s", simpleMsg);
            }

            @Override
            public void onSuccess(File response)
            {
                install(response);
            }
        });
    }

    private void install(File t)
    {
        startActivity(configIntent(t));
    }

    /***
     * 构建安装的意图
     * @param t
     * @return
     */
    private Intent configIntent(File t)
    {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.fromFile(t),
                "application/vnd.android.package-archive");
        return intent;
    }

    //通知栏显示进度
    private void showProgressInNotify(int progress)
    {
        if (isFirst)
        {
            mBuilder = new NotificationCompat.Builder(getApplicationContext());
            mBuilder.setSmallIcon(R.mipmap.ic_launcher);
            mBuilder.setAutoCancel(true);
            mBuilder.setContentTitle("版本更新");
            isFirst = false;
        }
        mBuilder.setContentText("下载进度: " + String.valueOf(progress) + "%");
        mBuilder.setProgress(100, progress, false);
        mNotiManager.notify(0, mBuilder.build());
    }


}
